package com.stu.wgt.test.service.Imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.wgt.test.bean.Pet;
import com.stu.wgt.test.bean.PetPicurl;
import com.stu.wgt.test.mapper.PetMapper;
import com.stu.wgt.test.mapper.PetPicurlMapper;
import com.stu.wgt.test.service.PetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@Service
public class PetServiceImpl extends ServiceImpl<PetMapper, Pet> implements PetService {

    @Autowired
    PetMapper petMapper;
    @Autowired
    PetPicurlMapper petPicurlMapper;

    @Override
    public int insert(Pet pet) {
        return petMapper.insert(pet);
    }

    @Override
    public int delete(int id) {
        return petMapper.deleteById(id);
    }

    @Override
    public int update(Pet pet) {
        QueryWrapper<Pet> qw = new QueryWrapper<>();
        qw.eq("id", pet.getId());
        return petMapper.update(pet, qw);
    }

    @Override
    public List<Pet> selectAllPet() {
        return petMapper.selectList(null);
    }

    @Override
    public List<Pet> selectById(int id) {
        QueryWrapper<Pet> qw = new QueryWrapper<>();
        qw.eq("id", id);
        return petMapper.selectList(qw);
    }

    @Override
    public List<Pet> selectByName(String username) {
        return null;
    }

    @Override
    public IPage<Pet> searchPet(String query, int pageNum, int pageSize) {
        Page<Pet> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Pet> qw = new QueryWrapper<>();
        qw.like("type", query);
        IPage<Pet> petIPage = petMapper.selectPage(page, qw);
        List<Pet> petList = petIPage.getRecords();
        for (Pet pet : petList) {
            List<PetPicurl> picList = petPicurlMapper.selectList(new QueryWrapper<PetPicurl>().eq("pet_id", pet.getId()));
            // 如果有图片数据，则关联第一张图片到产品对象中
            if (!picList.isEmpty()) {
                pet.setUrl(picList.get(0).getPetUrl());
            } else {
                pet.setUrl(null);
            }
        }
        return petIPage;
    }
}
